<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Knowledge extends MY_Controller
{

    protected $allNotes;

    public function __construct()
    {
        parent::__construct();
        $this->load->model('TopicUnit');
        $this->load->model('TopicDetection');
        $this->load->model('TopicAnswer');
        $this->load->model('TopicSlotInfo');
        $this->load->model('WordDict');
        $this->load->model('AnswerType');
        $this->load->model('TopicCache');
        $this->load->model('DemandGroup');
        $this->load->model('TopicQuestionType');
        $this->load->library('Curl');
        $this->load->library('Stock');
        $this->load->library('ChineseToPinyin');
    }

    /*
     * ------------------------------------
     * |
     * |页面加载部分
     * |
     * ------------------------------------
     */
    /* 词库默认页面 */
    public function getQuestionDefalut()
    {
        $this->load->view('home/open');
    }
    // 权限默认页面
    public function getOnlineDefalut()
    {
        $this->load->view('home/onlineOpen');
    }

    /* 问答页卡 */
    public function index()
    {
        $data['permissionCode'] = implode(',', $this->session->permissionCode);
        $this->load->view('knowledgeManager/questionMainComment', $data);
    }

    /* 问答库目录树 */
    public function questionCatalogTree()
    {
        $this->load->view('knowledgeManager/questionCatalogTree');
    }

    /* 右键菜单 */
    public function rightMenu1()
    {
        $this->load->view('knowledgeManager/rightMenu1');
    }

    /* 问答库新建条目 */
    public function questionDialog()
    {
        $this->load->view('knowledgeManager/questionDialog');
    }

    /* 问答库编辑条目 */
    public function questionEditDialog()
    {
        $this->load->view('knowledgeManager/questionEditDialog');
    }

    /*
     * ------------------------------------
     * |
     * |分类树和搜索部分
     * |1.分类树
     * |2.搜索
     * |
     * ------------------------------------
     */
    // 获取引导问句
    function getGuidance($id)
    {
        $word = $_REQUEST['word'];
        $unit = $this->TopicUnit->findOne(array(
            '_id' => new MongoId($id)
        ));
        $DemandGroup = $this->DemandGroup->findOne(array(
            'demander' => $unit['source']
        ));
        $sourceArr = $DemandGroup['content_group'];
        $result = $this->TopicUnit->find(array(
            'source' => array(
                '$in' => $sourceArr
            ),
            'topic_name' => new MongoRegex("/.*" . $word . ".*/i"),
            'is_leaf' => true,
            'is_valid' => true
        ), array(
            'topic_name'
        ));
        if (empty($result)) {
            $data['code'] = 0;
            $data['msg'] = '未查询到记录！';
        } else {
            foreach ($result as $k => $res) {
                $answer = $this->TopicAnswer->findOne(array(
                    'topic_id' => $res['_id']
                ));
                $result[$k]['answer'] = $answer['answer'];
            }
            $data['code'] = 1;
            $data['msg'] = '查询成功！';
            $data['data'] = $result;
        }
        echo json_encode($data);
    }
    
    // 判断权限
    private function treePermission($code)
    {
        $permission = $_SESSION['permission'];
        return strstr($permission['topic_id'], $code);
    }

    /* 分类树 */
    public function getClassificationTree()
    {
        $id = empty($_REQUEST['id']) ? 'ROOT' : $_REQUEST['id'];
        $res = array(
            'code' => 0,
            'msg' => ''
        );
        $conditon = array(
            'parents' => $id,
            'is_valid' => true
        );
        $tree = $this->TopicUnit->find($conditon);
        if (empty($tree)) {
            $res['msg'] = '未查询到记录';
            echo json_encode($res);
            return false;
        }
        
        $data = array();
        foreach ($tree as $k => $v) {
            if ($v['parents'] == 'ROOT' && ! $this->treePermission($v['_id'])) {
                continue;
            }
            if ($v['is_leaf']) {
                $temp['_id'] = $v['_id']; // id
                $temp['topic_name'] = $v['topic_name']; // 标准问题
                /* 获取句式 */
                $conditon = array(
                    'topic_id' => $v['_id'],
                    'is_valid' => true
                );
                $result = $this->TopicDetection->find($conditon);
                $patterns = ! empty($result) ? implode(',', $result[0]['patterns']) : '';
                // $patterns = implode(',', $result[0]['patterns']);
                $temp['patterns'] = $this->getPatternsOfChinese($patterns);
                /* 获取标准答案 */
                $conditon = array(
                    'topic_id' => $v['_id'],
                    'slots_info' => array(),
                    'is_valid' => true
                );
                $result = $this->TopicAnswer->find($conditon);
                $guidances = array();
                if ($result) {
                    
                    foreach ($result[0]['guidance_answer'] as $gan) {
                        $guidances[] = $gan['topic_name'];
                    }
                }
                $temp['guidances'] = $guidances;
                $temp['answer'] = empty($result[0]['answer']) ? '' : $result[0]['answer'];
                $sourceTemp = $this->TopicUnit->findOne(array(
                    'parents' => 'ROOT',
                    'source' => $v['source']
                ));
                $temp['source'] = $sourceTemp['topic_name'];
                $temp['close_tag'] = empty($result[0]['close_tag']) ? '' : $result[0]['close_tag'];
                $temp['close_tag'] = $temp['close_tag'] ? '否' : '是';
                $temp['operator'] = $v['operator'];
                $temp['update_time'] = date('Y-m-d H:i:s', $v['update_time']->sec);
            } else {
                $temp = $v;
                $conditon = array(
                    'parents' => $v['_id'],
                    'is_valid' => true,
                    'is_leaf' => false
                );
                $count = $this->TopicUnit->getCount($conditon);
                $temp['parentOfLeaf'] = $count ? false : true;
                unset($temp['parents'], $temp['update_time'], $temp['is_valid'], $temp['is_leaf'], $temp['operator']);
            }
            $data[] = $temp;
        }
        
        $res['code'] = 1;
        $res['msg'] = '查询成功！';
        $res['data'] = $data;
        echo json_encode($res);
    }

    public function getLeafUnit()
    {
        $showPage = 10;
        $id = empty($_REQUEST['id']) ? 'ROOT' : $_REQUEST['id'];
        $pageNum = $_REQUEST['pageNum'];
        $pageSet = $_REQUEST['pageSet'];
        $skip = ($pageNum - 1) * $pageSet;
        $res = array(
            'code' => 0,
            'msg' => ''
        );
        $conditon = array(
            'parents' => $id,
            'is_valid' => true
        );
        $totalCount = $this->TopicUnit->getCount($conditon);
        if ($totalCount % $pageSet == 0) {
            $totalPage = $totalCount / $pageSet;
        } else {
            $totalPage = intval($totalCount / $pageSet + 1);
        }
        $tree = $this->TopicUnit->find($conditon, array(), $pageSet, $skip);
        if (empty($tree)) {
            $res['msg'] = '未查询到记录';
            echo json_encode($res);
            return false;
        }
        
        $data = array();
        foreach ($tree as $k => $v) {
            if ($v['is_leaf']) {
                $temp['_id'] = $v['_id']; // id
                $temp['topic_name'] = $v['topic_name']; // 标准问题
                /* 获取句式 */
                $conditon = array(
                    'topic_id' => $v['_id'],
                    'is_valid' => true
                );
                $result = $this->TopicDetection->find($conditon);
                $patterns = ! empty($result[0]['patterns']) ? implode(',', $result[0]['patterns']) : '';
                $temp['patterns'] = $this->getPatternsOfChinese($patterns);
                /* 获取标准答案 */
                $conditon = array(
                    'topic_id' => $v['_id'],
                    'is_valid' => true
                );
                $result = $this->TopicAnswer->find($conditon);
                $guidances = array();
                if ($result) {
                    foreach ($result[0]['guidance_answer'] as $gan) {
                        $guidances[] = $gan['topic_name'];
                    }
                }
                $temp['guidances'] = $guidances;
                $answer = "";
                // 取标准答案用于显示，标准答案为空则取非空的任一一个答案
                foreach ($result as $rk => $rv) {
                    if (empty($rv['slots_info'])) {
                        if (! empty($rv['answer'])) {
                            $answer = $rv['answer'];
                        }
                    } else {
                        if (! empty($rv['answer']) && ! $answer) {
                            $answer = $rv['answer'];
                        }
                    }
                }
                $temp['answer'] = $answer;
                $sourceTemp = $this->TopicUnit->findOne(array(
                    'parents' => 'ROOT',
                    'source' => $v['source']
                ));
                $temp['source'] = $sourceTemp['topic_name'];
                $temp['close_tag'] = empty($result[0]['close_tag']) ? '是' : '否';
                $temp['operator'] = $v['operator'];
                $temp['update_time'] = date('Y-m-d H:i:s', $v['update_time']->sec);
            }
            $data[] = $temp;
        }
        
        $pageInfo['totalCount'] = $totalCount;
        $pageInfo['pageNum'] = $pageNum;
        $pageInfo['pageSet'] = $pageSet;
        $pageInfo['showPage'] = $showPage;
        $pageInfo['totalPage'] = $totalPage;
        $pageInfo['id'] = $id;
        
        $res['code'] = 1;
        $res['msg'] = '查询成功！';
        $res['data'] = $data;
        $res['page'] = $pageInfo;
        echo json_encode($res);
    }

    private function permisssionFilter()
    {
        $rootTopicId = $_SESSION['permission']['topic_id'];
        $rootTopicIdArr = explode(',', $rootTopicId);
        $source = array();
        foreach ($rootTopicIdArr as $topicId) {
            if (in_array($topicId, array(
                'content',
                'unit',
                'word'
            )))
                continue;
            $root = $this->TopicUnit->findOne(array(
                '_id' => new MongoId($topicId)
            ));
            if ($root) {
                $source[] = $root['source'];
            }
        }
        return $source;
    }

    public function searchQuestion()
    {
        $showPage = 10;
        $res = array(
            'code' => 0,
            'msg' => ''
        );
        $id = empty($_REQUEST['id']) ? 'ROOT' : $_REQUEST['id'];
        $type = empty($_REQUEST['type']) ? '1' : $_REQUEST['type'];
        $pageSet = $_REQUEST['pageSet'];
        $pageNum = $_REQUEST['pageNum'];
        $beginTime = empty($_REQUEST['beginTime']) ? '' : $_REQUEST['beginTime'];
        $endTime = empty($_REQUEST['endTime']) ? '' : $_REQUEST['endTime'];
        $username = empty($_REQUEST['username']) ? '' : $_REQUEST['username'];
        $skip = ($pageNum - 1) * $pageSet;
        $keyword = trim($_REQUEST['keyword']);
        // 转义正则表达式
        $keyword = preg_quote($keyword);
        switch ($type) {
            case 1:
                /* 逻辑句式 */
                $result = $this->searchOfDetection($id, $keyword, $beginTime, $endTime, $username);
                break;
            case 2:
                /* 标准问题 */
                $result = $this->searchOfUnit($id, $keyword, $beginTime, $endTime, $username);
                break;
            case 3:
                /* 标准答案 */
                $result = $this->searchOfAnswer($id, $keyword, $beginTime, $endTime, $username);
                break;
            case 4:
                /*槽位内容*/
                $result = $this->searchOfSlot($id, $keyword, $beginTime, $endTime, $username);
                break;
            case 5:
                /*缺省追问*/
                $result = $this->searchOfQueSheng($id, $keyword, $beginTime, $endTime, $username);
                break;
            case 6:
                /*引导问句*/
                $result = $this->searchOfGuidance($id, $keyword, $beginTime, $endTime, $username);
                break;
            default:
                $res['msg'] = '参数错误！';
                echo json_encode($res);
                return false;
        }
        $data = array();
        $result = array_unique($result);
        $totalCount = count($result);
        $result = array_slice($result, $skip, $pageSet);
        if ($totalCount % $pageSet == 0) {
            $totalPage = $totalCount / $pageSet;
        } else {
            $totalPage = intval($totalCount / $pageSet + 1);
        }
        if (! empty($result)) {
            $data = $this->getQuestion($result);
        }
        
        $pageInfo['totalCount'] = $totalCount;
        $pageInfo['pageNum'] = $pageNum;
        $pageInfo['pageSet'] = $pageSet;
        $pageInfo['showPage'] = $showPage;
        $pageInfo['totalPage'] = $totalPage;
        $pageInfo['id'] = $id;
        $pageInfo['keyword'] = $keyword;
        
        if (empty($data)) {
            $res['msg'] = '未查询到记录！';
        } else {
            $res['code'] = 1;
            $res['msg'] = '查询成功！';
            $res['data'] = $data;
            $res['page'] = $pageInfo;
        }
        echo json_encode($res);
    }

    /*
     * -----------------------------------
     * |
     * |问答部分
     * |1.添加
     * |2.编辑
     * |3.删除
     * |4.移动
     * |
     * -----------------------------------
     */
    
    /*
     * 叶子节点的还原
     */
    public function restoreLeafUnit()
    {
        $parents = $_REQUEST['parents'];
        $topicName = $_REQUEST['topicName'];
        $operator = $_SESSION['user']['username'];
        $unitCondition = array(
            'parents' => $parents,
            'topic_name' => $topicName
        );
        $unit = $this->TopicUnit->findOne($unitCondition);
        $condition = array(
            'topic_id' => (string) $unit['_id']
        );
        $updateData = array(
            'is_valid' => true,
            'update_time' => new MongoDate(),
            'operator' => $operator
        );
        // 还原unit表
        $newTopicUnit = $this->TopicUnit->update($unitCondition, $updateData);
        // 还原answer表
        $newTopicAnswer = $this->TopicAnswer->update($condition, $updateData);
        // 还原slot_info表
        $newTopicSlot = $this->TopicSlotInfo->update($condition, $updateData);
        // 还原topic_detection表
        $newTopicDetection = $this->TopicDetection->update($condition, $updateData);
        
        if ($newTopicUnit && $newTopicAnswer && $newTopicSlot && $newTopicDetection) {
            $data['code'] = 1;
            $data['msg'] = '还原成功！';
        } else {
            $data['code'] = 0;
            $data['msg'] = '还原失败！';
        }
        echo json_encode($data);
    }

    /*
     * 问答部分移动
     */
    public function moveLeafUnit()
    {
        $topicId = $_REQUEST['topicId'];
        $newParent = $_REQUEST['newParent'];
        $fatherInfo = $this->TopicUnit->findOne(array(
            "_id" => new MongoId($newParent)
        ));
        if (! $fatherInfo['source']) {
            $data['code'] = 0;
            $data['msg'] = "该节点还没有添加渠道，不能移动到该节点！";
            echo json_encode($data);
            return false;
        }
        // $isLastParent = $this->TopicUnit->findOne(array('parents'=>$newParent, 'is_leaf'=>false, 'is_valid'=>true));
        $isLastParent = $this->TopicUnit->findOne(array(
            'parents' => $newParent,
            'is_leaf' => false,
            'is_valid' => true
        ));
        if ($isLastParent) {
            $data['code'] = 0;
            $data['msg'] = "该节点还存在非叶子子节点，不能移动到该节点！";
            echo json_encode($data);
            return false;
        }
        $condition = array(
            'topic_id' => $topicId
        );
        $updateU = $this->TopicUnit->update(array(
            '_id' => new MongoId($topicId)
        ), array(
            'parents' => $newParent,
            'source' => $fatherInfo['source']
        ));
        $updateD = $this->TopicDetection->update($condition, array(
            'source' => $fatherInfo['source']
        ));
        // 为获取修改solr的信息(没有槽的情况才添加到solr中)
        if (! ($updateD && $updateU)) {
            
            $data['code'] = 0;
            $data['msg'] = "转移过程出现问题！";
        } else {
            $this->execScript($topicId);
            $data['code'] = 1;
            $data['msg'] = "转移成功";
        }
        echo json_encode($data);
    }

    /*
     * 问答部分删除
     */
    public function deleteLeafUnit()
    {
        $topicId = $_REQUEST['topicId'];
        $operator = $_SESSION['user']['username'];
        $condition = array(
            'topic_id' => $topicId
        );
        $updateData = array(
            'is_valid' => false,
            'update_time' => new MongoDate(),
            'operator' => $operator
        );
        
        // 逻辑删除unit
        $delUnit = $this->TopicUnit->update(array(
            '_id' => new MongoId($topicId)
        ), $updateData);
        // 逻辑删除detection
        $delDetection = $this->TopicDetection->update($condition, $updateData);
        // 逻辑删除answer
        $delAnswer = $this->TopicAnswer->update($condition, $updateData);
        // 逻辑删除slot
        $delSlot = $this->TopicSlotInfo->update($condition, $updateData);
        // 删除cache表
        $delCache = $this->TopicCache->update($condition, $updateData);
        if ($delUnit && $delDetection && $delAnswer && $delSlot && $delCache) {
            $this->execScript($topicId);
            $data['code'] = 1;
            $data['msg'] = '删除成功!';
        } else {
            $data['code'] = 0;
            $data['msg'] = '删除失败!';
        }
        echo json_encode($data);
    }

    /* 问答部分-添加 */
    
    /*
     * 标准问句推荐逻辑问句接口
     */
    public function getLogicQuesByUnit()
    {
        $centence = $_REQUEST['content'];
        $centence = urlencode($centence);
        $url = LOGIC_URL . $centence;
        $content = Curl::curl_post($url);
        if ($content['code'] == 0) {
            echo $content['data'];
        } else {
            $data['code'] = 2;
            $data['msg'] = '调用接口失败！';
            echo json_encode($data);
        }
    }

    /*
     * 渠道下拉接口
     */
    public function getSource()
    {
        $conditon = array(
            'parents' => 'ROOT',
            'is_valid' => TRUE,
            'source' => array(
                '$ne' => null
            )
        );
        $result = $this->TopicUnit->find($conditon);
        if (empty($result)) {
            $data['code'] = 2;
            $data['msg'] = '未查询到记录！';
        } else {
            $data['code'] = 1;
            $data['msg'] = '查询成功';
            $data['data'] = $result;
        }
        echo json_encode($data);
    }

    public function getSourceById()
    {
        $id = $_REQUEST['id'];
        $conditon = array(
            'parents' => 'ROOT',
            'is_valid' => TRUE,
            'source' => array(
                '$ne' => null
            )
        );
        if (empty($id)) {
            $result = $this->TopicUnit->find($conditon);
        } else {
            $parent = $this->TopicUnit->findOne(array(
                '_id' => new MongoId($id)
            ));
            $result = $this->TopicUnit->find($conditon);
            foreach ($result as $k => $unit) {
                if ($unit['source'] == $parent['source']) {
                    $unit['flag'] = 1;
                } else {
                    $unit['flag'] = 0;
                }
                $result[$k] = $unit;
            }
        }
        if (empty($result)) {
            $data['code'] = 2;
            $data['msg'] = '未查询到记录！';
        } else {
            $data['code'] = 1;
            $data['msg'] = '查询成功';
            $data['data'] = $result;
        }
        echo json_encode($data);
    }

    public function getAnswerTypeById()
    {
        $id = $_REQUEST['id'];
        $answerTypesArr = array();
        $flag = '';
        
        $answerTypes = $this->TopicQuestionType->find(array(
            'is_valid' => TRUE
        ));
        foreach ($answerTypes as $answerType) {
            $answerTypesTemp['name'] = $answerType['name'];
            $answerTypesTemp['question_type'] = $answerType['question_type'];
            $answerTypesArr[] = $answerTypesTemp;
        }
        if (! empty($id)) {
        $parent = $this->TopicUnit->findOne(array(
            '_id' => new MongoId($id)
        ));
        $rootUnit = $this->TopicUnit->findOne(array(
            'parents' => 'ROOT',
            'source' => $parent['source']
        ));
        $answerType = $this->AnswerType->findOne(array(
            'topic_id' => (string) $rootUnit['_id']
        ));
        $flag = $answerType['answer_type'];
        }
        if (empty($answerTypesArr)) {
            $data['code'] = 2;
            $data['msg'] = '未查询到记录！';
        } else {
            $data['code'] = 1;
            $data['msg'] = '查询成功';
            $data['data'] = $answerTypesArr;
            $data['flag'] = $flag;
        }
        echo json_encode($data);
    }

    /*
     * 获取槽内容接口
     */
    public function chechStock($word)
    {
        $pattern = '/^[0-9][0-9]+[0-9]$/';
        $isNumber = preg_match($pattern, $word);
        $stock = new Stock();
        if ($isNumber) {
            return $stock->checkCode($word);
        } else {
            return $stock->checkName($word);
        }
    }

    public function getWord()
    {
        $word = trim($_REQUEST['word']);
        if (empty($word)) {
            $data['code'] = 2;
            $data['msg'] = '未查询到记录！';
            echo json_encode($data);
            return false;
        }
        $word = str_replace(array(
            '{',
            '}',
            '(',
            ')',
            '（',
            '）'
        ), '', $word);
        $stockClass = $this->config->item('stock');
        $isStock = $this->chechStock($word);
        if ($isStock) {
            $stock = $this->WordDict->findOne(array(
                'word' => (string) $isStock['stockCode']
            ));
            $aGuFullType = strstr($stock['full_type'], '.' . $stock['parent_type'], true);
            $aGuCondition = array(
                'full_type' => $aGuFullType,
                'word' => $stock['parent_word']
            );
            $aGuResult = $this->WordDict->find($aGuCondition, array(
                'full_type',
                'full_word',
                'parent_word',
                'word',
                'synonyms'
            ));
            $aGuResult[0]['full_type'] = $stock['full_type'];
            $aGuResult[0]['full_word'] = $aGuResult[0]['full_word'] . '(' . $stockClass[$stock['full_type']] . ')';
            $condition = array(
                'word' => new MongoRegex("/.*" . $word . ".*/i"),
                'is_path' => false,
                'is_valid' => true
            );
            $res = $this->WordDict->find($condition, array(
                'full_type',
                'full_word',
                'parent_word',
                'word',
                'synonyms'
            ));
            $res = $this->sortWord($res, $word, 'parent_word');
            $res = array_slice($res, 0, 10);
            $result = array_merge($aGuResult, $res);
        } else {
            $condition = array(
                'word' => new MongoRegex("/.*" . $word . ".*/i"),
                'is_path' => false,
                'is_valid' => true
            );
            $result = $this->WordDict->find($condition, array(
                'full_type',
                'full_word',
                'parent_word',
                'word',
                'synonyms'
            ));
            $result = $this->sortWord($result, $word, 'parent_word');
            $result = array_slice($result, 0, 10);
        }
        
        foreach ($result as $k => $row) {
            $row['synonyms'] = implode(',', $row['synonyms']); // 同义词修改为字符串传过去
            $fullWord = $row['full_word'];
            $parentWord = $row['parent_word'];
            $lineOne = strstr($fullWord, '.'); // 去掉根ROOT，并在末尾添加.号
            $lineOne = str_replace('.', '/', $lineOne);
            $lineOne = str_replace($parentWord, ' {' . $parentWord . '}', $lineOne);
            $lineOne = $lineOne . ' :';
            $row['full_word'] = $lineOne;
            $result[$k] = $row;
        }
        
        if (empty($result)) {
            $data['code'] = 2;
            $data['msg'] = '未查询到记录！';
        } else {
            $data['code'] = 1;
            $data['msg'] = '查询成功';
            $data['data'] = $result;
        }
        echo json_encode($data);
    }
    // 将完全匹配的词放在最前面
    private function sortWord($wordArr, $word, $compareWord = 'word')
    {
        $index = 0;
        $length = count($wordArr);
        foreach ($wordArr as $k => $wordInfo) {
            if ($wordInfo[$compareWord] == $word) {
                $temp = $wordArr[$k];
                $wordArr[$k] = $wordArr[$index];
                $wordArr[$index] = $temp;
                $index ++;
            }
        }
        for ($i = $index; $i < $length; $i ++) {
            if ($wordArr[$i][$compareWord] != $word && in_array($word, $wordArr[$i]['synonyms'])) {
                $temp = $wordArr[$i];
                $wordArr[$i] = $wordArr[$index];
                $wordArr[$index] = $temp;
                $index ++;
            }
        }
        for ($i = $index; $i < $length; $i ++) {
            if (preg_match("/.*$word.*/", $wordArr[$i][$compareWord])) {
                $temp = $wordArr[$i];
                $wordArr[$i] = $wordArr[$index];
                $wordArr[$index] = $temp;
                $index ++;
            }
        }
        return $wordArr;
    }

    /*
     * 输入逻辑问句时，获取类似的逻辑问句接口
     */
    public function getLogicQues()
    {
        $requestWord = urldecode(trim($_REQUEST['keyWord']));
        $wordPaths = urldecode(empty($_REQUEST['wordPaths']) ? "" : $_REQUEST['wordPaths']);
        $oldWords = urldecode(empty($_REQUEST['oldWord']) ? "" : $_REQUEST['oldWord']);
        $resultOfKeyword = $this->dealKeyWord($requestWord); // 对获取的参数进行处理
        $keyWord = $resultOfKeyword['keyword'];
        
        $data = array();
        if ($keyWord == false) {
            $info = $this->isDeletePattern($requestWord, $wordPaths, $oldWords);
            if ($info) {
                $data['wordPath'] = $info['wordPath'];
                $data['oldWord'] = $info['oldWord'];
                $data['code'] = 3;
                $data['msg'] = '删除节点';
                $data['data'] = $data;
                echo json_encode($data);
                return false;
            } else {
                $data['code'] = 0;
                $data['msg'] = '没有找到检索的信息';
                echo json_encode($data);
                return false;
            }
        }
        $condition = array(
            'is_path' => false,
            'is_valid' => true,
            '$or' => array(
                array(
                    'synonyms' => new MongoRegex("/.*$keyWord.*/i")
                ),
                array(
                    'word' => new MongoRegex("/.*$keyWord.*/i")
                )
            )
        );
        $result = $this->WordDict->find($condition, array(
            'full_type',
            'full_word',
            'parent_word',
            'word',
            'synonyms'
        ));
        $findKeyWordArray = array();
        $result = $this->sortWord($result, $keyWord, 'parent_word');
        foreach ($result as $row) {
            $row['synonyms'] = implode(',', $row['synonyms']); // 同义词修改为字符串传过去
            $fullWord = $row['full_word'];
            $parentWord = $row['parent_word'];
            $lineOne = strstr($fullWord, '.'); // 去掉根ROOT，并在末尾添加.号
            $lineOne = str_replace('.', '/', $lineOne);
            $lineOne = str_replace($parentWord, ' {' . $parentWord . '}', $lineOne);
            $lineOne = $lineOne . ' :';
            $row['full_word'] = $lineOne;
            $tempWord = $this->getReplaceWord($requestWord, $resultOfKeyword, $parentWord);
            $row['wordPaths'] = $this->getWordPaths($wordPaths, $tempWord, $oldWords, $row['full_type']);
            $row['replaceWord'] = $tempWord;
            $findKeyWordArray[] = $row;
        }
        
        if ($findKeyWordArray) {
            $data['code'] = 1;
            $data['msg'] = '查找成功！';
            $data['data'] = $findKeyWordArray;
            $data['highLight'] = $keyWord;
        } else {
            $data['code'] = 0;
            $data['msg'] = '未查询到记录！';
        }
        echo json_encode($data);
    }

    private function isDeletePattern($requestWord, $wordPaths, $oldWords)
    {
        $pattern = "/\{([^\{\}]*)\}/"; // 匹配'{XXX}'
        $patternRequest = "/\{([^\{\}]*)\}?/"; // 匹配'{XXX}'
        preg_match_all($pattern, $wordPaths, $wordPathArr);
        preg_match_all($patternRequest, $requestWord, $requestWordArr);
        preg_match_all($pattern, $oldWords, $oldWordsArr);

        if (count($wordPathArr[1]) == count($requestWordArr[1])) {
            $isdele = false;
            // 判断{XX|XXX}的情况
            foreach ($wordPathArr[1] as $k => $wordPath) {
                $isDeleVertical = $this->isDeleVertical($wordPath, $requestWordArr[1][$k]);
                if ($isDeleVertical) {
                    $isdele = true;
                    $wordPathArr[0][$k] = "{" . $isDeleVertical . "}";
                }
            }

            if (! $isdele) {
                return false;
            } else {
                $result = array(
                    'wordPath' => implode('', $wordPathArr[0]),
                    'oldWord' => $requestWord
                );
                return $result;
            }
        } else {
            
            foreach ($wordPathArr[1] as $k => $wordPath) {
                // 因为$requestWordArr的长度小于$wordPathArr的长度，当删除的是最后一个{}时，应做相应处理
                $compareWord = isset($requestWordArr[0][$k]) ? $requestWordArr[0][$k] : '';
                $oldWordsArr[0][$k] = empty($oldWordsArr[0][$k]) ? '' : $oldWordsArr[0][$k];
                if ($compareWord != $oldWordsArr[0][$k]) {
                    // 处理{XXX|XXXX|的情况
                    $isContainVertical = $this->isContainVertical($wordPathArr[1][$k], $requestWord, $oldWordsArr[1][$k]);
                    if ($isContainVertical) {
                        $wordPathArr[0][$k] = "{" . $isContainVertical['wordPath'] . "}";
                        $oldWordsArr[0][$k] = "{" . $isContainVertical['oldWord'] . "}";
                        $tmpRequestWord = $requestWord;
                        $requestWord = implode('', $oldWordsArr[0]);
                    } else {
                        unset($wordPathArr[0][$k]);
                    }
                    break;
                }
            }
            
            $result = array(
                'wordPath' => implode('', $wordPathArr[0]),
                'oldWord' => (empty($tmpRequestWord) ? $requestWord : $tmpRequestWord)
            );
            
            /* 打个补丁，修复中间句式被删除的bug */
            $result = $this->detectionFilter($result);
            return $result;
        }
    }

    private function isContainVertical($wordPath, $requestWord, $oldWords)
    {
        if (strpos($wordPath, '|') === false) {
            return false;
        } else {
            $oldWordArr = explode('|', $oldWords);
            $wordPathArr = explode('|', $wordPath);
            $pattern = "/\{([^\{\}]*)\}/";
            $arr = preg_split($pattern, $requestWord);
            $verticalWord = '';
            foreach ($arr as $k) {
                $verticalWord = preg_replace(array(
                    '/\[([^\[\]]*)\]/',
                    '/\(([^\(\)]*)\)/',
                    '/（([^（）]*)）/'
                ), '', trim($k));
                if ($verticalWord == '') {
                    continue;
                } else {
                    break;
                }
            }
            $verticalWordArr = explode("|", str_replace('{', '', $verticalWord));

            foreach ($oldWordArr as $k => $oldWord) {
                $temp = empty($verticalWordArr[$k]) ? '' : $verticalWordArr[$k];
                if ($oldWord != $temp && '' != $temp) {
                    unset($wordPathArr[$k]);
                    unset($oldWordArr[$k]);
                }
            }
            return array(
                'wordPath' => implode('|', $wordPathArr),
                'oldWord' => implode("|", $oldWordArr)
            );
        }
    }

    private function isDeleVertical($wordPath, $requestWord)
    {
        if (strpos($wordPath, '|') !== false) {
            $wordpArr = array_filter(explode('|', $wordPath));
            $wordArr = array_filter(explode('|', $requestWord));
            if (count($wordArr) == count($wordpArr)) {
                return false;
            } else {
                foreach ($wordpArr as $k => $wordp) {
                    $parentWord = isset($wordArr[$k]) ? $wordArr[$k] : '';
                    $result = $this->WordDict->getCount(array(
                        'full_type' => $wordp,
                        'parent_word' => $parentWord
                    ));
                    if ($result < 1) {
                        unset($wordpArr[$k]);
                        break;
                    }
                }
                return implode('|', $wordpArr);
            }
        }
    }

    private function getWordPaths($wordPaths, $tempWord, $oldWords, $fullType)
    {  
        $pattern = "/\{([^{}]*)\}/"; // 匹配'{XXX}'
        $patternForOld = "/(?:\{([^{}]*)\})|(?:\{([^{}]*))/"; // 匹配'{XXX}'
        preg_match_all($pattern, $wordPaths, $wordPathArr);
        preg_match_all($pattern, $tempWord, $tempWordArr);
        preg_match_all($patternForOld, $oldWords, $oldWordsArr);
        $temp = count($wordPathArr[0]);
        
        foreach ($wordPathArr[1] as $k => $wordPath) {
            // 处理{XX|XX}的情况
            if (strpos($tempWordArr[1][$k], '|') !== false) {
                $wordPathArr[0][$k] = $this->handleVertical($wordPathArr[1][$k], $tempWordArr[1][$k], $oldWordsArr[1][$k], $fullType);
                continue;
            }
            if ($tempWordArr[1][$k] != $oldWordsArr[1][$k]) {
                if (count($wordPathArr[0]) != count($tempWordArr[0])) {
                    $temp = $k;
                    break;
                } else {
                    $wordPathArr[0][$k] = '{' . $fullType . '}';
                    break;
                }
            }
        }
        if (count($wordPathArr[0]) != count($tempWordArr[0])) {
            if ($temp == 0) {
                array_unshift($wordPathArr[0], '{' . $fullType . '}');
            } else {
                array_splice($wordPathArr[0], $temp, 0, '{' . $fullType . '}');
            }
        }
        
        $wordPathStr = implode('', $wordPathArr[0]);
        
        return $wordPathStr;
    }

    /* 处理{XX|XX}的情况，将逻辑问句和路径相对应 */
    private function handleVertical($wordPaths, $tempWord, $oldWords, $fullType)
    {
        if ($tempWord == $oldWords) {
            return "{" . $wordPaths . "}";
        }
        $wordPathsArr = explode('|', $wordPaths);
        $tempWordsArr = explode('|', $tempWord);
        if (count($wordPathsArr) == count($tempWordsArr)) {
            $wordPathsArr[count($wordPathsArr) - 1] = $fullType;
            return "{" . implode('|', $wordPathsArr) . "}";
        } elseif (count($wordPathsArr) < count($tempWordsArr)) {
            $wordPathsArr[count($wordPathsArr)] = $fullType;
            return "{" . implode('|', $wordPathsArr) . "}";
        } else {
            $countOfWordPathsArr = count($wordPathsArr);
            $countOfTempWordsArr = count($tempWordsArr);
            $difference = $countOfWordPathsArr - $countOfTempWordsArr;
            $difference = (1 == $difference) ? $difference : $difference - 1;
            array_splice($wordPathsArr, $difference);
            $wordPathsArr[] = $fullType;
            return "{" . implode('|', $wordPathsArr) . "}";
        }
    }

    private function dealKeyWord($param)
    {
        $keyword = '';
        $word = $param;
        $word .= '['; // 相当于给最后的{}元素添加一个结尾标记
        
        /* 做了一个替换，兼容中英文括号 */
        $pattern = array(
            "/（/",
            "/）/"
        );
        $replace = array(
            "(",
            ")"
        );
        $word = preg_replace($pattern, $replace, $word); // 被替换后的句式
        
        $pattern = "/{([^{}\[\]()]*)(?:\[|\{|\()/";
        preg_match_all($pattern, $word, $match);
        $keyword = reset($match[1]); // 取到匹配的第一个元素的值
        
        /* 查找是否存在分隔符号'|' */
        if (strpos($keyword, '|') !== false) {
            $tmepKeywordArray = explode('|', $keyword);
            $endValue = end($tmepKeywordArray);
            $keyword = $endValue;
        }
        
        if (! $keyword) {
            return false;
        }
        
        $result['keyword'] = $keyword;
        $result['original'] = reset($match[0]);
        return $result;
    }

    /**
     * getReplaceWord
     * :讲句式中的关键字替换成词类
     *
     * @param
     *            :string word 传过来的句式
     * @param
     *            :array resultOfWord 被解析后的句式
     * @param
     *            ：string replaceWord 待替换的词汇
     * @return :array word:被替换后的句式 word_type:被替换后的路径（存的是id）
     */
    private function getReplaceWord($word, $resultOfWord, $replaceWord)
    {
        $result = '';
        $tempWord = $word . "[";
        
        /* 做了一个替换，兼容中英文括号 */
        $pattern = array(
            "/（/",
            "/）/"
        );
        $replace = array(
            "(",
            ")"
        );
        $word = preg_replace($pattern, $replace, $word); // 被替换后的句式
        
        /**
         * 为了避免替换到其余部分的词汇，这里关键字替换做了两步操作
         * 1.查看模式中是否存在'|',存在则将其解析，不存在则直接替换
         * 2.1中的替换是在局部替换，即模式中，得到局部替换完成后的字符串再到整个大的模式中进行替换
         * 3.2中在替换的时候自动识别了词汇是在尾部还是在中部，并且自动添加上了'}'作为结尾
         */
        /* 第一步替换局部替换 */
        $flag = strpos($resultOfWord['original'], '|');
        if ($flag === false) {
            $result = str_replace($resultOfWord['keyword'], $replaceWord, $resultOfWord['original']);
        } else {
            $result = '{';
            $tempOriginal = $resultOfWord['original'];
            $endChar = substr($tempOriginal, - 1);
            $tempOriginal = substr($tempOriginal, 0, - 1);
            $tempOriginal = trim($tempOriginal, '{');
            $OriginalArray = explode('|', $tempOriginal);
            $count = count($OriginalArray);
            $OriginalArray[$count - 1] = $replaceWord;
            foreach ($OriginalArray as $value) {
                $result .= $value . '|';
            }
            $result = rtrim($result, '|') . $endChar;
        }
        /* 第二步替换整体替换 */
        $flag = strpos($word, $resultOfWord['original']);
        if ($flag === false) {
            $result = trim($result, '[') . '}';
            $result = str_replace($resultOfWord['original'], $result, $tempWord);
        } else {
            $endChar = substr($result, - 1);
            $result = substr($result, 0, - 1) . "}$endChar";
            $result = str_replace($resultOfWord['original'], $result, $word);
        }
        return $result;
    }

    /*
     * 未添加槽时添加问句
     */
    public function addLeafUnit()
    {
        $topicName = $_REQUEST['topicName'];
        $answer = $_REQUEST['answer'];
        $interactionType = empty($_REQUEST['interactionType']) ? '' : $_REQUEST['interactionType'];
        $displayAnswer = empty($_REQUEST['displayAnswer']) ? '' : $_REQUEST['displayAnswer'];
        $answerType = $_REQUEST['answerType'];
        $parents = $_REQUEST['parents'];
        $parentUnit = $this->isInitSource($parents);
        if (! $parentUnit) {
            $data['code'] = 0;
            $data['msg'] = '该父节点未初始化渠道！';
            $data['data'] = array(
                'parents' => $parents,
                'topic_name' => $topicName
            );
            echo json_encode($data);
            return false;
        }
        $exist = $this->TopicUnit->getCount(array(
            'parents' => $parents,
            'topic_name' => $topicName
        ));
        if ($exist > 0) {
            $data['code'] = 0;
            $data['msg'] = '该父节点下已经存在“' . $topicName . '”的问句';
            $data['data'] = array(
                'parents' => $parents,
                'topic_name' => $topicName
            );
            echo json_encode($data);
            return false;
        }
        $requestPatterns = $_REQUEST['patterns'];
        $operator = $_SESSION['user']['username'];
        $greeting = $_REQUEST['greeting'] == 1 ? false : true;
        $source = $_REQUEST['source'];
        foreach ($requestPatterns as $k => $v) {
            $k = urldecode($k);
            $patterns[] = $this->replacePatterns($v, $k);
        }
        
        // 获取guidance_answer字段
        $guidanceAnswers = array();
        $requestGuidances = empty($_REQUEST['guidances']) ? array() : $_REQUEST['guidances'];
        foreach ($requestGuidances as $guidance) {
            $guidancesTemp['topic_id'] = $guidance[0];
            $guidancesTemp['topic_name'] = $guidance[1];
            $guidancesTemp['alias'] = $guidance[2];
            $guidanceAnswers[] = $guidancesTemp;
        }
        
        // 存表topic_unit
        $insertUnit = array(
            'parents' => $parents,
            'topic_name' => $topicName,
            'is_leaf' => true,
            'update_time' => new MongoDate(),
            'is_valid' => true,
            'operator' => $operator,
            'source' => $source
        );
        $newUnit = $this->TopicUnit->insert($insertUnit);
        $topicId = $insertUnit['_id']->{'$id'};
        // 存表topic_detection
        $insertDetection = array(
            'topic_id' => $topicId,
            'topic_name' => $topicName,
            'match_algorithm' => "rule_extract",
            'patterns' => $patterns,
            'update_time' => new MongoDate(),
            'is_valid' => true,
            'operator' => $operator,
            'source' => $source
        );
        $newDetection = $this->TopicDetection->insert($insertDetection);
        
        // 存表topic_answer
        $insertAnswer = array(
            'topic_id' => $topicId,
            'topic_name' => $topicName,
            'slots_info' => array(),
            'user_profile' => array(),
            'global_info' => array(),
            'answer_type' => $answerType,
            'answer' => $answer,
            'guidance_answer' => $guidanceAnswers,
            'display_type' => $interactionType,
            'display_answer' => $displayAnswer,
            'close_tag' => $greeting,
            'update_time' => new MongoDate(),
            'is_valid' => true,
            'operator' => $operator
        );
        $newAnswer = $this->TopicAnswer->insert($insertAnswer);
        if ($newAnswer && $newDetection && $newUnit) {
            $this->execScript($topicId);
            $info['id'] = $topicId;
            $info['operator'] = $operator;
            $info['updateTime'] = date('Y-m-d H:i:s', time());
            $info['topicName'] = $topicName;
            $info['answerType'] = $answerType;
            $info['answer'] = $answer;
            $info['guidanceAnswers'] = $guidanceAnswers;
            $info['interactionType'] = $interactionType;
            $info['displayAnswer'] = $displayAnswer;
            $data['data'] = $info;
            $data['code'] = 1;
            $data['msg'] = '添加成功';
        } else {
            $data['code'] = 0;
            $data['msg'] = '添加失败';
        }
        echo json_encode($data);
    }
    
    // 执行脚本方法
    private function execScript($id, $oldId = '')
    {
        if ($oldId == '') {
            $url = base_url() . "/cron/SolrServer.php?id=$id";
        } else {
            $url = base_url() . "/cron/SolrServer.php?id=$id&oldId=$oldId";
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 1);
        curl_exec($ch);
        curl_close($ch);
    }
    
    // 判断传过来的patterns是否对应
    private function patternsIsMaping($patterns)
    {
        foreach ($patterns as $type => $word) {
            $typePat = "/\{(ROOT[^(\})]*)\}/";
            $wordPat = "/\{([^(\})]*)\}/";
            preg_match_all($typePat, urldecode($type), $typeArr);
            preg_match_all($wordPat, $word, $wordArr);
            if (count($typeArr[1]) != count($wordArr[1])) {
                return false;
            }
        }
        return true;
    }
    
    // 将{}里面的词语替换为全路径
    private function replacePatterns($patterns, $patternTypes)
    {
        $pat = "/\{([^(\})]*)\}/";
        preg_match_all($pat, $patternTypes, $mat);
        foreach ($mat[0] as $k => $v) {
            $pat = '/{[^{}.]+}/';
            $patterns = preg_replace($pat, $v, $patterns, 1);
        }
        $patterns = str_replace(array(
            '（',
            '）'
        ), array(
            '(',
            ')'
        ), $patterns);
        return $patterns;
    }

    /*
     * 同时添加槽和问句
     */
    function addLeafUnitWithSlot()
    {
        $slots = $_REQUEST['slots'];
        $topicName = $_REQUEST['topicName'];
        $answerType = $_REQUEST['answerType'];
        $answers = $_REQUEST['answers'];
        $parents = $_REQUEST['parents'];
        $interactionType = empty($_REQUEST['interactionType']) ? '' : $_REQUEST['interactionType'];
        $displayAnswer = empty($_REQUEST['displayAnswer']) ? '' : $_REQUEST['displayAnswer'];
        if (! $this->isInitSource($parents)) {
            $data['code'] = 0;
            $data['msg'] = '该父节点未初始化渠道！';
            $data['data'] = array(
                'parents' => $parents,
                'topic_name' => $topicName
            );
            echo json_encode($data);
            return false;
        }
        $exist = $this->TopicUnit->getCount(array(
            'parents' => $parents,
            'topic_name' => $topicName
        ));
        if ($exist > 0) {
            $data['code'] = 0;
            $data['msg'] = '该父节点下已经存在“' . $topicName . '”的问句';
            $data['data'] = array(
                'parents' => $parents,
                'topic_name' => $topicName
            );
            echo json_encode($data);
            return false;
        }
        // 获取guidances_answer字段
        $guidanceAnswers = array();
        $requestGuidances = empty($_REQUEST['guidances']) ? array() : $_REQUEST['guidances'];
        foreach ($requestGuidances as $guidance) {
            $guidancesTemp['topic_id'] = $guidance[0];
            $guidancesTemp['topic_name'] = $guidance[1];
            $guidancesTemp['alias'] = $guidance[2];
            $guidanceAnswers[] = $guidancesTemp;
        }
        
        $operator = $_SESSION['user']['username'];
        $greeting = $_REQUEST['greeting'] == 1 ? false : true;
        $source = $_REQUEST['source'];
        $requestPatterns = $_REQUEST['patterns'];
        $slotNa = '';
        foreach ($slots as $slotName) {
            $slotNa .= "[" . $slotName[0] . "]";
        }
        foreach ($requestPatterns as $k => $v) {
            $k = urldecode($k);
            $pattern = $this->replacePatterns($v, $k);
            $patterns[] = $pattern . $slotNa;
        }
        $newAnswer = $newDetection = $newUnit = $newSlot = $newTopicCache = true;
        // 存表topic_unit
        $insertUnit = array(
            'parents' => $parents,
            'topic_name' => $topicName,
            'is_leaf' => true,
            'update_time' => new MongoDate(),
            'is_valid' => true,
            'operator' => $operator,
            'source' => $source
        );
        $newUnit = $this->TopicUnit->insert($insertUnit);
        $topicId = $insertUnit['_id']->{'$id'};
        // 存表topic_detection
        $insertDetection = array(
            'topic_id' => $topicId,
            'topic_name' => $topicName,
            'match_algorithm' => "rule_extract",
            'patterns' => $patterns,
            'update_time' => new MongoDate(),
            'is_valid' => true,
            'operator' => $operator,
            'source' => $source
        );
        $stockArr = $this->config->item('stock');
        $newDetection = $this->TopicDetection->insert($insertDetection);
        $pat = "/\[([^(\])]*)\]/"; // 匹配'[XXX]' ;
                                   // 存表topic_answer
        foreach ($answers as $answer) {
            $answer[1] = trim($answer[1]);
            if (empty($answer[1])) {
                continue;
            }
            $slotsInfos = array();
            preg_match_all($pat, $answer[0], $conditionSlot);
            foreach ($conditionSlot[1] as $slotsInfo) {
                $slot = array();
                $slot[] = strstr($slotsInfo, '.', true);
                $slot[] = substr(strstr($slotsInfo, '.'), 1);
                if ($slot[1] == '空') {
                    continue;
                }
                if (in_array($slot[1], $stockArr)) {
                    $filterPlugin = 'belogTo';
                } else {
                    $filterPlugin = 'equal';
                }
                $slotsInfos[] = array(
                    'filter_plugin' => $filterPlugin,
                    'parameter' => $slot[1],
                    'slot_name' => $slot[0]
                );
            }
            if (empty($slotsInfos)) {
                $interactionTypeInsert = $interactionType;
                $displayAnswerInsert = $displayAnswer;
            } else {
                $interactionTypeInsert = '';
                $displayAnswerInsert = '';
            }
            $insert_answer = array(
                'topic_id' => $topicId,
                'topic_name' => $topicName,
                'slots_info' => $slotsInfos,
                'user_profile' => array(),
                'global_info' => array(),
                'answer_type' => $answerType,
                'answer' => $answer[1],
                'guidance_answer' => $guidanceAnswers,
                'display_type' => $interactionTypeInsert,
                'display_answer' => $displayAnswerInsert,
                'close_tag' => $greeting,
                'update_time' => new MongoDate(),
                'is_valid' => true,
                'operator' => $operator
            );
            $newAnswer = $this->TopicAnswer->insert($insert_answer);
        }
        // 存表topic_slot_info
        foreach ($slots as $slot) {
            $slotType = array();
            foreach ($slot[1] as $k => $v) {
                if ($k == '空') {
                    continue;
                }
                $slotType[] = $v;
            }
            $slotType = array_unique($slotType);
            $slotType = array_merge($slotType);
            $insertSlot = array(
                'topic_id' => $topicId,
                'topic_name' => $topicName,
                'slot_name' => $slot[0],
                'slot_type' => $slotType,
                'slot_property' => array(),
                'slot_content' => array(),
                'default_value' => '',
                'ask_type' => 'common',
                'ask_condition' => array(),
                'question' => array(
                    $slot[2]
                ),
                'update_time' => new MongoDate(),
                'is_valid' => true,
                'operator' => $operator
            );
            $newSlot = $this->TopicSlotInfo->insert($insertSlot);
            $slotIds[] = $insertSlot['_id']->{'$id'};
        }
        
        // 存表topic_cache
        foreach ($slotIds as $k => $slotId) {
            $updateSlotInfo = array();
            foreach ($slots[$k][1] as $k => $v) {
                if ($k == '空') {
                    continue;
                }
                $updateSlotInfo = array(
                    "slot_id" => $slotId,
                    "slot_type" => $v,
                    "slot_content" => (string) $k
                );
                $topicCache = $this->TopicCache->getCount(array(
                    'topic_id' => $topicId
                ));
                if ($topicCache > 0) {
                    $newTopicCache = $this->TopicCache->selfUpdate(array(
                        'topic_id' => $topicId
                    ), array(
                        '$push' => array(
                            'slot_infos' => $updateSlotInfo
                        )
                    ));
                } else {
                    $insertTopicCache = array(
                        'topic_name' => $topicName,
                        'topic_id' => $topicId,
                        'patters_word' => '',
                        'slot_infos' => array(
                            $updateSlotInfo
                        ),
                        'update_time' => new MongoDate(),
                        'operator' => 'sys'
                    );
                    $newTopicCache = $this->TopicCache->insert($insertTopicCache);
                }
            }
        }
        if ($newAnswer && $newDetection && $newUnit && $newSlot && $newTopicCache) {
            $info['id'] = $topicId;
            $info['operator'] = $operator;
            $info['updateTime'] = date('Y-m-d H:i:s', time());
            $data['data'] = $info;
            $data['code'] = 1;
            $data['msg'] = '添加成功';
        } else {
            $data['code'] = 0;
            $data['msg'] = '添加失败';
        }
        echo json_encode($data);
    }

    /*
     * 判断父节点是否存在渠道
     */
    private function isInitSource($id)
    {
        if ($id == '' || $id == 'ROOT') {
            return true;
        }
        $parentUnit = $this->TopicUnit->findOne(array(
            '_id' => new MongoId($id)
        ));
        return ! empty($parentUnit['source']) ? $parentUnit : false;
    }

    /* 问答部分-编辑 */
    
    /*
     * 保存存在条件槽的编辑数据
     */
    public function saveEditLeafUnitWithSlot()
    {
        $topicName = $_REQUEST['topicName'];
        $answers = $_REQUEST['answers'];
        $topicId = $_REQUEST['topicId'];
        $operator = $_SESSION['user']['username'];
        $greeting = $_REQUEST['greeting'] == 1 ? false : true;
        $source = $_REQUEST['source'];
        $answerType = $_REQUEST['answerType'];
        $interactionType = empty($_REQUEST['interactionType']) ? '' : $_REQUEST['interactionType'];
        $displayAnswer = empty($_REQUEST['displayAnswer']) ? '' : $_REQUEST['displayAnswer'];
        $requestPatterns = $_REQUEST['patterns'];
        foreach ($requestPatterns as $k => $v) {
            $k = urldecode($k);
            $patterns[] = $this->replacePatterns($v, $k);
        }
        
        // 获取guidances_answer字段
        $guidanceAnswers = array();
        if (! empty($_REQUEST['guidances'])) {
            foreach ($_REQUEST['guidances'] as $guidance) {
                $guidancesTemp['topic_id'] = $guidance[0];
                $guidancesTemp['topic_name'] = $guidance[1];
                $guidancesTemp['alias'] = $guidance[2];
                $guidanceAnswers[] = $guidancesTemp;
            }
        }
        
        $condition = array(
            'topic_id' => $topicId
        );
        // 存表topic_unit
        $updateUnit = array(
            'topic_name' => $topicName,
            'update_time' => new MongoDate(),
            'operator' => $operator,
            'source' => $source
        );
        $newUnit = $this->TopicUnit->update(array(
            '_id' => new MongoId($topicId)
        ), $updateUnit);
        // 存表topic_detection
        $presentDetection = $this->TopicDetection->findOne($condition);
        if ($patterns != $presentDetection['patterns']) {
            foreach ($patterns as $k => $pattern) {
                $pat = '/\[[^][]+\]/';
                $pattern = preg_replace($pat, '', $pattern);
                preg_match_all($pat, $presentDetection['patterns'][0], $matchArr);
                $pattern .= implode('', $matchArr[0]);
                $patterns[$k] = $pattern;
            }
        }
        $updateDetection = array(
            'topic_name' => $topicName,
            'patterns' => $patterns,
            'update_time' => new MongoDate(),
            'operator' => $operator,
            'source' => $source
        );
        $newDetection = $this->TopicDetection->update($condition, $updateDetection);
        // 修改answer表的topicName
        $updateTopicName = array(
            'topic_name' => $topicName,
            'answer_type' => $answerType,
            'update_time' => new MongoDate(),
            'guidance_answer' => $guidanceAnswers,
            'operator' => $operator
        );
        $newAnswer = $this->TopicAnswer->update($condition, $updateTopicName, array(
            'multiple' => true
        ));
        $pat = "/\[([^(\])]*)\]/"; // 匹配'[XXX]' ;
        $newAnswer = true;
        $stockArr = $this->config->item('stock'); // 获取特殊股票，保存answer表中slot_info.filter_plugin
                                                  // 存表topic_answer
        foreach ($answers as $answer) {
            $slotsInfos = array();
            preg_match_all($pat, $answer[0], $conditionSlot);
            $parameterArr = array();
            $slotNameArr = array();
            foreach ($conditionSlot[1] as $slotsInfo) {
                $slot = array();
                $slot[] = strstr($slotsInfo, '.', true);
                $slot[] = substr(strstr($slotsInfo, '.'), 1);
                // 如果槽位为空，且提交的答案只有一个，则更新其他答案closeTag
                if ($slot[1] == '空') {
                    if (count($answers) == 1) {
                        $otherCondition = array(
                            "topic_id" => $_REQUEST['topicId'],
                            "is_valid" => true
                        );
                        $otherAnswer = $this->TopicAnswer->find($otherCondition);
                        foreach ($otherAnswer as $ok => $ov) {
                            $cond = array(
                                "_id" => new MongoId($ov['_id'])
                            );
                            $this->TopicAnswer->update($cond, array(
                                'close_tag' => $greeting
                            ));
                        }
                    }
                    continue;
                }
                $parameterArr[] = $slot[1];
                $slotNameArr[] = $slot[0];
                if (in_array($slot[1], $stockArr)) {
                    $filterPlugin = 'belogTo';
                } else {
                    $filterPlugin = 'equal';
                }
                $slotsInfos[] = array(
                    'filter_plugin' => $filterPlugin,
                    'parameter' => $slot[1],
                    'slot_name' => $slot[0]
                );
            }
            $isExistAnswer = $this->isExistAnswer($topicId, $parameterArr, $slotNameArr);
            if (trim($answer[1]) == null && ! $isExistAnswer) {
                continue;
            }
            // slots_info为空才存这个两个字段，负责这两个字段为空
            if (empty($slotsInfos)) {
                $interactionTypeInsert = $interactionType;
                $displayAnswerInsert = $displayAnswer;
            } else {
                $interactionTypeInsert = '';
                $displayAnswerInsert = '';
            }
            
            if ($isExistAnswer) {
                $updateAnswer = array(
                    'topic_name' => $topicName,
                    'slots_info' => $slotsInfos,
                    'answer' => $answer[1],
                    'display_type' => $interactionTypeInsert,
                    'display_answer' => $displayAnswerInsert,
                    'close_tag' => $greeting,
                    'update_time' => new MongoDate(),
                    'guidance_answer' => $guidanceAnswers,
                    'operator' => $operator
                );
                if (empty($parameterArr)) {
                    $answerCondition = array(
                        'topic_id' => $topicId,
                        'slots_info' => array()
                    );
                } else {
                    $answerCondition = array(
                        'topic_id' => $topicId,
                        'slots_info.parameter' => array(
                            '$all' => $parameterArr
                        ),
                        'slots_info.slot_name' => array(
                            '$all' => $slotNameArr
                        ),
                        'slots_info' => array(
                            '$size' => count($slotNameArr)
                        )
                    );
                }
                $newAnswer = $this->TopicAnswer->update($answerCondition, $updateAnswer);
            } else {
                $insertAnswer = array(
                    "topic_id" => $topicId,
                    "topic_name" => $topicName,
                    "slots_info" => $slotsInfos,
                    "user_profile" => array(),
                    "global_info" => array(),
                    "answer_type" => $answerType,
                    "answer" => $answer[1],
                    'guidance_answer' => $guidanceAnswers,
                    'display_type' => $interactionTypeInsert,
                    'display_answer' => $displayAnswerInsert,
                    "close_tag" => true,
                    "update_time" => new MongoDate(),
                    "is_valid" => true,
                    "operator" => $operator
                );
                
                $newAnswer = $this->TopicAnswer->insert($insertAnswer);
            }
        }
        // 更新slot_info表的名字
        $updateSlot = array(
            'topic_name' => $topicName,
            'update_time' => new MongoDate(),
            'operator' => $operator
        );
        $newSlot = $this->TopicSlotInfo->update($condition, $updateSlot, array(
            'multiple' => true
        ));
        if ($newAnswer && $newDetection && $newUnit && $newSlot) {
            $info['id'] = $topicId;
            $info['operator'] = $operator;
            $info['updateTime'] = date('Y-m-d H:i:s', time());
            $info['topicName'] = $topicName;
            $info['slotsInfos'] = $slotsInfos;
            $info['answer'] = $answer[1];
            $info['guidanceAnswers'] = $guidanceAnswers;
            $info['interactionTypeInsert'] = isset($interactionTypeInsert) ? $interactionTypeInsert : '';
            $info['displayAnswerInsert'] = isset($displayAnswerInsert) ? $displayAnswerInsert : '';
            
            $data['data'] = $info;
            $data['code'] = 1;
            $data['msg'] = '添加成功';
        } else {
            $data['code'] = 0;
            $data['msg'] = '添加失败';
        }
        echo json_encode($data);
    }

    public function isExistAnswer($topicId, $parameterArr, $slotNameArr)
    {
        if (empty($parameterArr)) {
            $condition = array(
                'topic_id' => $topicId,
                'slots_info' => array()
            );
        } else {
            $condition = array(
                'topic_id' => $topicId,
                'slots_info.parameter' => array(
                    '$all' => $parameterArr
                ),
                'slots_info.slot_name' => array(
                    '$all' => $slotNameArr
                ),
                'slots_info' => array(
                    '$size' => count($slotNameArr)
                )
            );
        }
        $answer = $this->TopicAnswer->findOne($condition);
        return $answer;
    }

    /*
     * 选择槽内容时
     */
    /* * ********************************************** */
    public function showAnswer()
    {
        $topicId = $_REQUEST['topicId'];
        $slotss = is_array($_REQUEST['slotss']) ? $_REQUEST['slotss'] : array();
        $pat = "/\[([^(\])]*)\]/";
        $res = array();
        foreach ($slotss as $slots) {
            $parameter = array();
            $slotName = array();
            preg_match_all($pat, $slots, $conditionSlot);
            foreach ($conditionSlot[1] as $slot) {
                $tempCondition = array();
                $tempCondition[] = strstr($slot, '.', true);
                $tempCondition[] = substr(strstr($slot, '.'), 1);
                if ($tempCondition[1] == '空') {
                    continue;
                }
                $parameter[] = $tempCondition[1];
                $slotName[] = $tempCondition[0];
            }
            $answer = $this->isExistAnswer($topicId, $parameter, $slotName);
            
            $res[$slots] = $answer;
        }
        
        if ($res) {
            $data['code'] = 1;
            $data['msg'] = '查询成功';
            $data['data'] = $res;
        } else {
            $data['code'] = 0;
            $data['msg'] = '未查询到数据';
        }
        echo json_encode($data);
    }

    /*
     * 点击编辑
     */
    public function editLeafUnit()
    {
        $topicId = $_REQUEST['topicId'];
        $answer = $this->TopicAnswer->findOne(array(
            'topic_id' => $topicId
        ));
        $data['answer'] = $answer['answer'];
        // 目前同一topicname下的所有guidance_answer都是一样的
        $data['guidances'] = $answer['guidance_answer'];
        $data['interactionType'] = $answer['display_type'];
        $data['displayAnswer'] = $answer['display_answer'];
        $data['answerType'] = $answer['answer_type'];
        $condition = array(
            'topic_id' => $topicId
        );
        if ($answer['close_tag']) {
            $data['greeting'] = '否';
        } else {
            $data['greeting'] = '是';
        }
        $detection = $this->TopicDetection->findOne($condition);
        $data['topicName'] = $detection['topic_name'];
        $data['source'] = $detection['source'];
        $data['patternTypes'] = $detection['patterns'];
        $cache = $this->TopicCache->findOne($condition);
        if ($cache && false) {
            $data['patterns'] = $cache['patters_word'];
        } else {
            foreach ($detection['patterns'] as $k => $v) {
                $patterns[] = $this->getPatterns($v);
            }
            $data['patterns'] = $patterns;
        }
        
        // 槽部分
        $slotArr = array();
        $slots = $this->TopicSlotInfo->find($condition);
        if (count($slots) > 0) {
            foreach ($slots as $slot) {
                $temp = array();
                $temp['_id'] = $slot['_id'];
                $temp['slotName'] = $slot['slot_name'];
                $temp['question'] = implode('', $slot['question']);
                foreach ($cache['slot_infos'] as $kk => $vv) {
                    if ($vv['slot_id'] == (string) $slot['_id']) {
                        $temp['content'][$vv['slot_content']] = $vv['slot_type'];
                    }
                }
                $slotArr[] = $temp;
            }
            if ($slotArr) {
                $data['slots'] = $slotArr;
                $answer = $this->TopicAnswer->findOne(array(
                    'topic_id' => $topicId,
                    'slots_info' => array()
                ));
                $data['answer'] = $answer['answer'];
                $data['interactionType'] = $answer['display_type'];
            }
        }
        
        $result['code'] = 1;
        $result['msg'] = '查询成功';
        $result['data'] = $data;
        echo json_encode($result);
    }
    
    // 根据全路径，获取parents_word,并且将其对应起来
    private function getPatterns($pattern)
    {
        $pat = "/\{([^(\})]*)\}/"; // 匹配'{XXX}'
        $patternStr = $pattern;
        preg_match_all($pat, $pattern, $patternArr);
        foreach ($patternArr[1] as $k => $v) {
            $types = explode('|', $v); // 考虑到{XXX|XXX}这中情况
            $parentWordArr = array();
            foreach ($types as $type) {
                $wordDict = $this->WordDict->findOne(array(
                    'full_type' => $type
                ));
                $parentWordArr[] = $wordDict['parent_word'];
            }
            $patternStr = str_replace('{' . $v . '}', '{' . implode("|", $parentWordArr) . '}', $patternStr);
        }
        return array(
            $pattern => $patternStr
        );
    }

    /*
     * 保存编辑的数据
     */
    public function saveEditLeafUnit()
    {
        $topicId = trim($_REQUEST['topicId']);
        $topicName = trim($_REQUEST['topicName']);
        $answer = trim($_REQUEST['answer']);
        $interactionType = trim($_REQUEST['interactionType']);
        $displayAnswer = trim($_REQUEST['displayAnswer']);
        $source = $_REQUEST['source'];
        $answerType = $_REQUEST['answerType'];
        $operator = $_SESSION['user']['username'];
        $greeting = $_REQUEST['greeting'] == 1 ? false : true;
        $requestPatterns = $_REQUEST['patterns'];
        foreach ($requestPatterns as $k => $v) {
            $k = urldecode($k);
            $patterns[] = $this->replacePatterns($v, $k);
        }
        // 后面修改solr需要
        $Unit = $this->TopicUnit->findOne(array(
            '_id' => new MongoId($topicId)
        ));
        // 改表topic_unit
        $updateUnit = array(
            'topic_name' => $topicName,
            'update_time' => new MongoDate(),
            'operator' => $operator,
            'source' => $source
        );
        $newUnit = $this->TopicUnit->update(array(
            '_id' => new MongoId($topicId)
        ), $updateUnit);
        $condition = array(
            'topic_id' => $topicId
        );
        // 存表topic_detection
        $presentDetection = $this->TopicDetection->findOne($condition);
        if ($patterns != $presentDetection['patterns']) {
            foreach ($patterns as $k => $pattern) {
                $pat = '/\[[^][]+\]/';
                $pattern = preg_replace($pat, '', $pattern);
                preg_match_all($pat, $presentDetection['patterns'][0], $matchArr);
                $pattern .= implode('', $matchArr[0]);
                $patterns[$k] = $pattern;
            }
        }
        $updateDetection = array(
            'topic_name' => $topicName,
            'patterns' => $patterns,
            'update_time' => new MongoDate(),
            'operator' => $operator,
            'source' => $source
        );
        $newDetection = $this->TopicDetection->update($condition, $updateDetection);
        
        // 获取guidance_answer字段
        $guidanceAnswers = array();
        $requestGuidances = empty($_REQUEST['guidances']) ? array() : $_REQUEST['guidances'];
        $requestGuidances = empty($_REQUEST['guidances']) ? array() : $_REQUEST['guidances'];
        foreach ($requestGuidances as $guidance) {
            $guidancesTemp['topic_id'] = $guidance[0];
            $guidancesTemp['topic_name'] = $guidance[1];
            $guidancesTemp['alias'] = $guidance[2];
            $guidanceAnswers[] = $guidancesTemp;
        }
        
        // 存表topic_answer
        $updateAnswer = array(
            'topic_name' => $topicName,
            'answer' => $answer,
            'guidance_answer' => $guidanceAnswers,
            'display_type' => $interactionType,
            'display_answer' => $displayAnswer,
            'answer_type' => $answerType,
            'close_tag' => $greeting,
            'update_time' => new MongoDate(),
            'operator' => $operator
        );
        $newAnswer = $this->TopicAnswer->update($condition, $updateAnswer);
        if ($newAnswer && $newDetection && $newUnit) {
            $this->execScript($topicId, md5($Unit['topic_name'] . $Unit['source']));
            $info['id'] = $topicId;
            $info['operator'] = $operator;
            $info['updateTime'] = date('Y-m-d H:i:s', time());
            $info['answerType'] = $answerType;
            $info['displayAnswer'] = $displayAnswer;
            $info['interactionType'] = $interactionType;
            $info['answer'] = $answer;
            $info['topicName'] = $topicName;
            $info['guidanceAnswers'] = $guidanceAnswers;
            $data['data'] = $info;
            $data['code'] = 1;
            $data['msg'] = '修改成功';
        } else {
            $data['code'] = 0;
            $data['msg'] = '修改失败';
        }
        echo json_encode($data);
    }

    /*
     * 增加槽
     */
    public function addSlot()
    {
        $topicId = $_REQUEST['topicId'];
        $slots = $_REQUEST['slot'];
        $slotName = $_REQUEST['slotName'];
        $question = $_REQUEST['question'];
        $operator = $_SESSION['user']['username'];
        foreach ($slots as $v) {
            foreach ($v as $kk => $vv) {
                $slot[$kk] = $vv;
            }
        }
        // 修改detection表的patterns字段
        $detection = $this->TopicDetection->findOne(array(
            'topic_id' => $topicId
        ));
        $patterns = $detection['patterns'];
        foreach ($patterns as $k => $pattern) {
            $patterns[$k] = $pattern . "[$slotName]";
        }
        
        // 添加slot_info表
        $slotType = array();
        foreach ($slot as $k => $v) {
            if ($k == '空') {
                continue;
            }
            $slotType[] = $v;
        }
        $slotType = array_unique($slotType);
        $slotType = array_merge($slotType);
        $insertSlot = array(
            'topic_id' => $topicId,
            'topic_name' => $detection['topic_name'],
            'slot_name' => $slotName,
            'slot_type' => $slotType,
            'slot_property' => array(),
            'slot_content' => array(),
            'default_value' => '',
            'ask_type' => 'common',
            'ask_condition' => array(),
            'question' => array(
                $question
            ),
            'update_time' => new MongoDate(),
            'is_valid' => true,
            'operator' => $operator
        );
        $newSlot = $this->TopicSlotInfo->insert($insertSlot);
        $newDetection = true;
        if ($newSlot) {
            $newDetection = $this->TopicDetection->update(array(
                "_id" => $detection['_id']
            ), array(
                'patterns' => $patterns
            ));
        }
        $slotId = (string) $insertSlot['_id'];
        // 在cache表中增加新的slot_infos
        $updateSlotInfo = array();
        foreach ($slot as $k => $v) {
            $updateSlotInfo = array(
                "slot_id" => $slotId,
                "slot_type" => $v,
                "slot_content" => (string) $k
            );
            $topicCache = $this->TopicCache->getCount(array(
                'topic_id' => $topicId
            ));
            if ($topicCache > 0) {
                $newTopicCache = $this->TopicCache->selfUpdate(array(
                    'topic_id' => $topicId
                ), array(
                    '$push' => array(
                        'slot_infos' => $updateSlotInfo
                    )
                ));
            } else {
                $insertTopicCache = array(
                    'topic_name' => $detection['topic_name'],
                    'topic_id' => $topicId,
                    'patters_word' => '',
                    'slot_infos' => array(
                        $updateSlotInfo
                    ),
                    'update_time' => new MongoDate(),
                    'operator' => $operator
                );
                $newTopicCache = $this->TopicCache->insert($insertTopicCache);
            }
        }
        
        if ($newSlot && $newDetection) {
            $this->execScript($topicId);
            $data['code'] = 1;
            $data['msg'] = '添加成功';
            $data['id'] = $slotId;
        } else {
            $data['code'] = 0;
            $data['msg'] = '添加失败';
        }
        echo json_encode($data);
    }

    /*
     * 删除槽
     */
    public function deleteSlot()
    {
        $slotId = $_REQUEST['slotId'];
        $slot = $this->TopicSlotInfo->findOne(array(
            '_id' => new MongoId($slotId)
        ));
        $cache = $this->TopicCache->findOne(array(
            'topic_id' => $slot['topic_id']
        ));
        
        // 修改Detection表的patterns字段
        $detection = $this->TopicDetection->findOne(array(
            'topic_id' => $slot['topic_id']
        ));
        foreach ($detection['patterns'] as $k => $pattern) {
            $patterns[$k] = str_replace("[" . $slot['slot_name'] . "]", '', $pattern);
        }
        $newDetection = $this->TopicDetection->update(array(
            "_id" => $detection['_id']
        ), array(
            'patterns' => $patterns
        ));
        
        foreach ($cache['slot_infos'] as $slotInfos) {
            if ($slotInfos['slot_id'] == $slotId) {
                $slotTypeArr[] = $slotInfos['slot_content'];
            }
        }
        $condition = array(
            'topic_id' => $slot['topic_id'],
            'slot_info' => array(
                '$ne' => array()
            ),
            'slots_info.parameter' => array(
                '$in' => $slotTypeArr
            )
        );
        // 删除slot_info的相关记录
        $result1 = $this->TopicSlotInfo->remove(array(
            '_id' => new MongoId($slotId)
        ));
        // 删除answer中的相关记录
        $retult2 = $this->TopicAnswer->remove($condition);
        // 更新cache表
        $retult3 = $this->TopicCache->selfUpdate(array(
            'topic_id' => $slot['topic_id']
        ), array(
            '$pull' => array(
                'slot_infos' => array(
                    'slot_id' => $slotId
                )
            )
        ));
        if ($result1 && $retult2 && $retult3 && $newDetection) {
            $this->execScript($slot['topic_id']);
            $data['code'] = 0;
            $data['msg'] = '删除成功';
        } else {
            $data['code'] = 0;
            $data['msg'] = '删除成功';
        }
        echo json_encode($data);
    }

    /*
     * 保存槽编辑后的数据
     */
    public function saveEditSlot()
    {
        $operator = $_SESSION['user']['username'];
        $slotName = trim($_REQUEST['slotName']);
        $question = trim($_REQUEST['question']);
        $slot = $_REQUEST['slot'];
        $slotId = $_REQUEST['slotId'];
        $topicId = $_REQUEST['topicId'];
        $presentSlot = $this->TopicSlotInfo->findOne(array(
            '_id' => new MongoId($slotId)
        ));
        foreach ($slot as $k => $v) {
            if ($v == null) {
                continue;
            }
            $slotContent[] = $k;
        }
        // 删除parameter不在$slotContent里面的answer
        $delAnswers = $this->TopicAnswer->find(array(
            'topic_id' => $topicId,
            'slots_info' => array(
                '$ne' => array()
            ),
            'slots_info.slot_name' => array(
                '$all' => array(
                    $presentSlot['slot_name']
                )
            ),
            'slots_info.parameter' => array(
                '$nin' => $slotContent
            )
        ));
        $rmAnswer = true;
        foreach ($delAnswers as $delAnswer) {
            $rmAnswer = $this->TopicAnswer->remove(array(
                '_id' => new MongoId($delAnswer['_id'])
            ));
        }
        
        // 修改detection表
        if ($slotName != $presentSlot['slot_name']) {
            $presentDetection = $this->TopicDetection->findOne(array(
                'topic_id' => $topicId
            ));
            $patterns = array();
            foreach ($presentDetection['patterns'] as $k => $v) {
                $patterns[] = str_replace("[" . $presentSlot['slot_name'] . "]", "[$slotName]", $v);
            }
            $this->TopicDetection->update(array(
                'topic_id' => $topicId
            ), array(
                'patterns' => $patterns
            ));
            // 修改answer表的slot_name字段
            $answerCondition = array(
                'topic_id' => $topicId,
                'slots_info.slot_name' => $presentSlot['slot_name']
            );
            $newAnswer = $this->TopicAnswer->update($answerCondition, array(
                'slots_info.$.slot_name' => $slotName
            ), array(
                'multiple' => true
            ));
        }
        
        // 存表topic_slot_info
        
        $slotType = array();
        foreach ($slot as $k => $v) {
            if (empty($k) || empty($v)) {
                continue;
            }
            $slotType[] = $v;
        }
        $slotType = array_unique($slotType);
        $slotType = array_merge($slotType);
        $updateSlot = array(
            'slot_name' => $slotName,
            'slot_type' => $slotType,
            'question' => array(
                $question
            ),
            'update_time' => new MongoDate(),
            'operator' => $operator
        );
        $newSlot = $this->TopicSlotInfo->update(array(
            '_id' => new MongoId($slotId)
        ), $updateSlot);
        
        // 存topic_cache表
        $newTopicCache = $this->TopicCache->selfUpdate(array(
            'topic_id' => $topicId
        ), array(
            '$pull' => array(
                'slot_infos' => array(
                    'slot_id' => $slotId
                )
            )
        ));
        // 保存新增的slot_type
        foreach ($slot as $k => $v) {
            if ($k == null) {
                continue;
            }
            $updateSlotInfo = array(
                "slot_id" => $slotId,
                "slot_type" => $v,
                "slot_content" => (string) $k
            );
            $newCache = $this->TopicCache->selfUpdate(array(
                'topic_id' => $topicId
            ), array(
                '$push' => array(
                    'slot_infos' => $updateSlotInfo
                )
            ));
        }
        
        if ($rmAnswer && $newSlot && $newCache && $newTopicCache) {
            $data['code'] = 1;
            $data['msg'] = '修改成功';
        } else {
            $data['code'] = 0;
            $data['msg'] = '修改失败';
        }
        echo json_encode($data);
    }

    /*
     * -----------------------------------
     * |
     * |目录树部分
     * |1.添加
     * |2.编辑
     * |3.删除
     * |
     * -----------------------------------
     */
    
    /* 添加分类 */
    public function addTypeset()
    {
        $id = $_REQUEST['id'];
        $typeset = trim($_REQUEST['typeset']);
        $operator = $_SESSION['user']['username'];
        $res = array(
            'code' => 0,
            'msg' => ''
        );
        $parentTree = $this->isInitSource($id);
        if (! $parentTree) {
            $res['msg'] = '该父节点未初始化渠道！';
            echo json_encode($res);
            return false;
        }
        if (empty($id)) {
            $id = 'ROOT';
        }
        if (empty($typeset)) {
            $res['msg'] = '分类名不能为空！';
            echo json_encode($res);
            return false;
        }
        /* 添加部分 */
        $condition = array(
            'parents' => $id,
            'topic_name' => $typeset
        );
        
        $result = $this->TopicUnit->find($condition);
        /* 未查询到该记录，直接添加 */
        if (empty($result)) {
            $value = array(
                'parents' => $id,
                'topic_name' => $typeset,
                'is_leaf' => false,
                'update_time' => new MongoDate(),
                'is_valid' => true,
                'operator' => $operator,
                'source' => $parentTree['source']
            );
            $flag = $this->TopicUnit->insert($value);
            $newParentId = $value['_id']->{'$id'};
            $this->moveChildrenToNewNode($id, $newParentId);
            if ($flag) {
                $data['id'] = $newParentId;
                $res['code'] = 1;
                $res['msg'] = '添加分类成功！';
                $res['data'] = $data;
            } else {
                $res['msg'] = '添加失败！';
            }
            echo json_encode($res);
            return false;
        }
        
        /* 查询到记录的情况:1.没被删除的直接提示；2.删除过的先恢复 */
        $unit = $result[0];
        if ($unit['is_valid'] === true) {
            $res['msg'] = '当前分类已经存在！';
            echo json_encode($res);
            return false;
        }
        
        $value = array(
            'update_time' => new MongoDate(),
            'is_valid' => true,
            'operator' => $operator
        );
        $updateTypeset = $this->TopicUnit->update($condition, $value);
        $res['code'] = 1;
        $res['msg'] = '添加分类成功！';
        echo json_encode($res);
    }

    /* 删除分类 */
    public function deleteTypeset()
    {
        $id = $_REQUEST['id'];
        $operator = $_SESSION['user']['username'];
        $res = array(
            'code' => 0,
            'msg' => ''
        );
        if (empty($id)) {
            $res['msg'] = 'id不能为空！';
            echo json_encode($res);
            return false;
        }
        
        $child = $this->getAllChildNode($id); // 获取所有相关子目录
        $allNode = array(); // 所有结点id集合
        $leafNode = array(); // 叶子结点id集合
        if (! empty($child)) {
            foreach ($child as $v) {
                if ($v['is_leaf']) {
                    $leafNode[] = $v['_id'];
                }
                $allNode[] = new MongoId($v['_id']);
            }
        }
        $allNode[] = new MongoId($id); // 将当前分类加入
        
        $value = array(
            'is_valid' => false,
            'operator' => $operator,
            'update_time' => new MongoDate()
        );
        /* 修改topic_unit表 */
        $condition = array(
            '_id' => array(
                '$in' => $allNode
            )
        );
        $result1 = $this->TopicUnit->update($condition, $value, true);
        /* 修改answer,detection,slot_info表 */
        $condition = array(
            'topic_id' => array(
                '$in' => $leafNode
            )
        );
        if ($result1 && $leafNode) {
            $result2 = $this->TopicAnswer->update($condition, $value, true);
            $result3 = $this->TopicDetection->update($condition, $value, true);
            $result4 = $this->TopicSlotInfo->update($condition, $value, true);
            foreach ($leafNode as $topicId) {
                $this->execScript((string) $topicId);
            }
        }
        $res['code'] = 1;
        $res['msg'] = '删除成功！';
        echo json_encode($res);
    }

    /* 编辑分类 */
    public function editTypeset()
    {
        $id = $_REQUEST['id'];
        $newTypeset = trim($_REQUEST['newTypeset']);
        $operator = $_SESSION['user']['username'];
        $res = array(
            'code' => 0,
            'msg' => ''
        );
        if (empty($id)) {
            $res['msg'] = 'id不能为空！';
            echo json_encode($res);
            return false;
        } elseif (empty($newTypeset)) {
            $res['msg'] = '分类名不能为空！';
            echo json_encode($res);
            return false;
        }
        $condition = array(
            '_id' => new MongoId($id)
        );
        $value = array(
            'topic_name' => $newTypeset,
            'update_time' => new MongoDate(),
            'operator' => $operator
        );
        $result = $this->TopicUnit->update($condition, $value);
        if ($result) {
            $res['code'] = 1;
            $res['msg'] = '修改成功！';
        } elseif ($result === false) {
            $res['msg'] = '修改失败，当前分类名已经存在，请使用其他分类名！';
        } else {
            $res['msg'] = '修改失败！';
        }
        echo json_encode($res);
    }

    /*
     * -----------------------
     * |
     * |其他一些公用函数
     * |
     * -----------------------
     */
    
    /* 获取所有相关结点的信息 */
    private function getAllChildNode($id)
    {
        $res = array();
        $condition = array(
            'parents' => $id,
            'is_valid' => true
        );
        $child = $this->TopicUnit->find($condition);
        if ($child) {
            foreach ($child as $v) {
                $temp = array(
                    '_id' => $v['_id'],
                    'is_leaf' => $v['is_leaf']
                );
                $res[] = $temp;
                $temp = $this->getAllChildNode($v['_id']);
                if (! empty($temp)) {
                    foreach ($temp as $v1) {
                        $res[] = $v1;
                    }
                }
            }
        }
        return $res;
    }

    /* 逻辑句式的搜索 */
    private function searchOfDetection($id, $keyword, $beginTime, $endTime, $username)
    {
        $source = $this->permisssionFilter();
        $pattern1 = new MongoRegex("/[(\[][^)\]]*{$keyword}[^)\]]*[)\]]/"); // 匹配（）[]中的内容，模糊匹配
        $keywordType = ChineseToPinyin::getCapital($keyword);
        $pattern2 = new MongoRegex("/[{|.]{$keywordType}[|}]/"); // 匹配{}中的内容，精确匹配
        $condition = array(
            'source' => array(
                '$in' => $source
            ),
            'is_valid' => true,
            '$or' => array(
                array(
                    'patterns' => $pattern1
                ),
                array(
                    'patterns' => $pattern2
                )
            )
        );
        // 关键词是否为空
        
        // 根据输入时间段，拼接搜索条件
        if (! empty($beginTime) && ! empty($endTime)) {
            $condition['update_time'] = array(
                '$gte' => new MongoDate($beginTime),
                '$lte' => new MongoDate($endTime)
            );
        } else 
            if (empty($beginTime) && ! empty($endTime)) {
                $condition['update_time'] = array(
                    '$lte' => new MongoDate($endTime)
                );
            } else 
                if (! empty($beginTime) && empty($endTime)) {
                    $condition['update_time'] = array(
                        '$gte' => new MongoDate($beginTime)
                    );
                }
        // 根据姓名输入，添加搜索条件
        if (! empty($username)) {
            $condition['operator'] = $username;
        }
        /* 获取当前目录下的叶子结点id集合 */
        if ($id != 'ROOT') {
            $child = $this->getAllChildNode($id);
            $childLeafNode = array();
            foreach ($child as $v) {
                if ($v['is_leaf']) {
                    $childLeafNode[] = $v['_id'];
                }
            }
            $conditionOfId = array(
                '$in' => $childLeafNode
            );
        }
        if (! empty($childLeafNode)) {
            $condition['topic_id'] = $conditionOfId;
        }
        
        $result = $this->TopicDetection->find($condition);
        $data = array();
        foreach ($result as $v) {
            $data[] = $v['topic_id'];
        }
        return $data;
    }

    /* 标准问句的搜索 */
    private function searchOfUnit($id, $keyword, $beginTime, $endTime, $username)
    {
        $source = $this->permisssionFilter();
        $pattern = new MongoRegex("/.*$keyword.*/");
        $condition = array(
            'source' => array(
                '$in' => $source
            ),
            'topic_name' => $pattern,
            'is_valid' => true,
            'is_leaf' => true
        );
        // 根据输入时间段，拼接搜索条件
        if (! empty($beginTime) && ! empty($endTime)) {
            $condition['update_time'] = array(
                '$gte' => new MongoDate($beginTime),
                '$lte' => new MongoDate($endTime)
            );
        } else 
            if (empty($beginTime) && ! empty($endTime)) {
                $condition['update_time'] = array(
                    '$lte' => new MongoDate($endTime)
                );
            } else 
                if (! empty($beginTime) && empty($endTime)) {
                    $condition['update_time'] = array(
                        '$gte' => new MongoDate($beginTime)
                    );
                }
        // 根据姓名输入，添加搜索条件
        if (! empty($username)) {
            $condition['operator'] = $username;
        }
        /* 获取当前目录下的叶子结点id集合 */
        if ($id != 'ROOT') {
            $child = $this->getAllChildNode($id);
            $childLeafNode = array();
            foreach ($child as $v) {
                if ($v['is_leaf']) {
                    $childLeafNode[] = new MongoId($v['_id']);
                }
            }
            $conditionOfId = array(
                '$in' => $childLeafNode
            );
        }
        if (! empty($childLeafNode)) {
            $condition['_id'] = $conditionOfId;
        }
        
        $result = $this->TopicUnit->find($condition);
        $data = array();
        foreach ($result as $v) {
            $data[] = $v['_id'];
        }
        return $data;
    }

    /*
     * 槽缺省搜索
     */
    private function searchOfQueSheng($id, $keyword, $beginTime, $endTime, $username)
    {
        $source = $this->permisssionFilter();
        $pattern = new MongoRegex("/.*{$keyword}.*/");
        $condition = array(
            "is_valid" => true,
            'question' => $pattern
        );
        // 根据输入时间段，拼接搜索条件
        if (! empty($beginTime) && ! empty($endTime)) {
            $condition['update_time'] = array(
                '$gte' => new MongoDate($beginTime),
                '$lte' => new MongoDate($endTime)
            );
        } else 
            if (empty($beginTime) && ! empty($endTime)) {
                $condition['update_time'] = array(
                    '$lte' => new MongoDate($endTime)
                );
            } else 
                if (! empty($beginTime) && empty($endTime)) {
                    $condition['update_time'] = array(
                        '$gte' => new MongoDate($beginTime)
                    );
                }
        
        // 根据姓名输入，添加搜索条件
        if (! empty($username)) {
            $condition['operator'] = $username;
        }
        /* 获取当前目录下的叶子结点id集合 */
        if ($id != 'ROOT') {
            $child = $this->getAllChildNode($id);
            $childLeafNode = array();
            foreach ($child as $v) {
                if ($v['is_leaf']) {
                    $childLeafNode[] = $v['_id'];
                }
            }
            $conditionOfId = array(
                '$in' => $childLeafNode
            );
        }
        if (! empty($childLeafNode)) {
            $condition['topic_id'] = $conditionOfId;
        }
        $result = $this->TopicSlotInfo->find($condition);
        $data = array();
        foreach ($result as $v) {
            $unit = $this->TopicUnit->findOne(array(
                '_id' => new MongoId($v['topic_id']),
                'source' => array(
                    '$in' => $source
                )
            ));
            if ($unit) {
                $data[] = $v['topic_id'];
            }
        }
        return $data;
    }

    /*
     * 槽位内容搜索
     */
    private function searchOfSlot($id, $keyword, $beginTime, $endTime, $username)
    {
        // $keywordType = ChineseToPinyin::getCapital($keyword);
        // $pattern = new MongoRegex("/{$keywordType}[^.]*$/");//这里是精确匹配
        $source = $this->permisssionFilter();
        $pattern = new MongoRegex("/.*{$keyword}.*/"); // 这里是精确匹配
        $condition = array(
            'is_valid' => array(
                '$ne' => false
            ),
            'slot_infos.slot_content' => $pattern
        );
        // 根据输入时间段，拼接搜索条件
        if (! empty($beginTime) && ! empty($endTime)) {
            $condition['update_time'] = array(
                '$gte' => new MongoDate($beginTime),
                '$lte' => new MongoDate($endTime)
            );
        } else 
            if (empty($beginTime) && ! empty($endTime)) {
                $condition['update_time'] = array(
                    '$lte' => new MongoDate($endTime)
                );
            } else 
                if (! empty($beginTime) && empty($endTime)) {
                    $condition['update_time'] = array(
                        '$gte' => new MongoDate($beginTime)
                    );
                }
        
        // 根据姓名输入，添加搜索条件
        if (! empty($username)) {
            $condition['operator'] = $username;
        }
        /* 获取当前目录下的叶子结点id集合 */
        if ($id != 'ROOT') {
            $child = $this->getAllChildNode($id);
            $childLeafNode = array();
            foreach ($child as $v) {
                if ($v['is_leaf']) {
                    $childLeafNode[] = $v['_id'];
                }
            }
            $conditionOfId = array(
                '$in' => $childLeafNode
            );
        }
        if (! empty($childLeafNode)) {
            $condition['topic_id'] = $conditionOfId;
        }
        $result = $this->TopicCache->find($condition);
        $data = array();
        foreach ($result as $v) {
            $unit = $this->TopicUnit->findOne(array(
                '_id' => new MongoId($v['topic_id']),
                'source' => array(
                    '$in' => $source
                )
            ));
            if ($unit) {
                $data[] = $v['topic_id'];
            }
        }
        return $data;
    }

    private function searchOfGuidance($id, $keyword, $beginTime, $endTime, $username)
    {
        $source = $this->permisssionFilter();
        $pattern = new MongoRegex("/.*{$keyword}.*/"); // 这里是精确匹配
        $condition = array(
            'is_valid' => array(
                '$ne' => false
            ),
            'guidance_answer.topic_name' => $pattern
        );
        // 根据输入时间段，拼接搜索条件
        if (! empty($beginTime) && ! empty($endTime)) {
            $condition['update_time'] = array(
                '$gte' => new MongoDate($beginTime),
                '$lte' => new MongoDate($endTime)
            );
        } else 
            if (empty($beginTime) && ! empty($endTime)) {
                $condition['update_time'] = array(
                    '$lte' => new MongoDate($endTime)
                );
            } else 
                if (! empty($beginTime) && empty($endTime)) {
                    $condition['update_time'] = array(
                        '$gte' => new MongoDate($beginTime)
                    );
                }
        // 根据姓名输入，添加搜索条件
        if (! empty($username)) {
            $condition['operator'] = $username;
        }
        /* 获取当前目录下的叶子结点id集合 */
        if ($id != 'ROOT') {
            $child = $this->getAllChildNode($id);
            $childLeafNode = array();
            foreach ($child as $v) {
                if ($v['is_leaf']) {
                    $childLeafNode[] = $v['_id'];
                }
            }
            $conditionOfId = array(
                '$in' => $childLeafNode
            );
        }
        if (! empty($childLeafNode)) {
            $condition['topic_id'] = $conditionOfId;
        }
        $result = $this->TopicAnswer->find($condition);
        $data = array();
        foreach ($result as $v) {
            $unit = $this->TopicUnit->findOne(array(
                '_id' => new MongoId($v['topic_id']),
                'source' => array(
                    '$in' => $source
                )
            ));
            if ($unit) {
                $data[] = $v['topic_id'];
            }
        }
        return $data;
    }

    /* 标准答案的搜索 */
    private function searchOfAnswer($id, $keyword, $beginTime, $endTime, $username)
    {
        $source = $this->permisssionFilter();
        $pattern = empty($keyword) ? '' : new MongoRegex("/.*$keyword.*/");
        $condition = array(
            'answer' => $pattern,
            'is_valid' => true
        );
        // 根据输入时间段，拼接搜索条件
        if (! empty($beginTime) && ! empty($endTime)) {
            $condition['update_time'] = array(
                '$gte' => new MongoDate($beginTime),
                '$lte' => new MongoDate($endTime)
            );
        } else 
            if (empty($beginTime) && ! empty($endTime)) {
                $condition['update_time'] = array(
                    '$lte' => new MongoDate($endTime)
                );
            } else 
                if (! empty($beginTime) && empty($endTime)) {
                    $condition['update_time'] = array(
                        '$gte' => new MongoDate($beginTime)
                    );
                }
        
        // 根据姓名输入，添加搜索条件
        if (! empty($username)) {
            $condition['operator'] = $username;
        }
        /* 获取当前目录下的叶子结点id集合 */
        if ($id != 'ROOT') {
            $child = $this->getAllChildNode($id);
            $childLeafNode = array();
            foreach ($child as $v) {
                if ($v['is_leaf']) {
                    $childLeafNode[] = $v['_id'];
                }
            }
            $conditionOfId = array(
                '$in' => $childLeafNode
            );
        }
        if (! empty($childLeafNode)) {
            $condition['topic_id'] = $conditionOfId;
        }
        
        $result = $this->TopicAnswer->find($condition);
        $data = array();
        foreach ($result as $v) {
            $unit = $this->TopicUnit->findOne(array(
                '_id' => new MongoId($v['topic_id']),
                'source' => array(
                    '$in' => $source
                )
            ));
            if ($unit) {
                $data[] = $v['topic_id'];
            }
        }
        return $data;
    }

    /* 获取问答信息 */
    private function getQuestion($topicId)
    {
        $data = array();
        foreach ($topicId as $id) {
            $conditon = array(
                'is_valid' => true,
                'topic_id' => $id
            );
            $result = $this->TopicDetection->find($conditon);
            $detection = $result[0];
            // $conditon['slots_info'] = array();
            $result = $this->TopicAnswer->find($conditon);
            $guidances = array();
            if ($result) {
                foreach ($result[0]['guidance_answer'] as $gan) {
                    $guidances[] = $gan['topic_name'];
                }
            }
            $temp['guidances'] = $guidances;
            
            if ($result) {
                $answer = $result[0];
            } else {
                $answer = array(
                    'answer' => '',
                    'close_tag' => ''
                );
            }
            $temp['_id'] = $id;
            $patterns = ! empty($detection['patterns']) ? implode(',', $detection['patterns']) : '';
            $temp['patterns'] = $this->getPatternsOfChinese($patterns);
            $temp['topic_name'] = $detection['topic_name'];
            // $temp['answer'] = htmlspecialchars($answer['answer']);
            $temp['answer'] = $answer['answer'];
            if (empty($detection['source'])) {
                $temp['source'] = "";
            } else {
                $sourceTemp = $this->TopicUnit->findOne(array(
                    'parents' => 'ROOT',
                    'source' => $detection['source']
                ));
                $temp['source'] = $sourceTemp['topic_name'];
            }
            $temp['close_tag'] = $answer['close_tag'] ? '否' : '是';
            $temp['operator'] = $detection['operator'];
            $temp['update_time'] = date('Y-m-d H:i:s', $detection['update_time']->sec);
            $data[] = $temp;
        }
        return $data;
    }

    /* 解析逻辑句式，将其转换成中文路径 */
    private function getPatternsOfChinese($string)
    {
        $preg = "/{([^}]*)}/";
        preg_match_all($preg, $string, $matches);
        $sentence = $matches[1];
        $field = array(
            'parent_word'
        );
        foreach ($sentence as $k => $v) {
            $temp = array();
            $partArray = explode('|', $v);
            /* 解析全路径 */
            foreach ($partArray as $fullType) {
                $condtion = array(
                    'full_type' => $fullType
                );
                $result = $this->WordDict->find($condtion, $field, 1);
                $temp[] = empty($result[0]['parent_word']) ? $fullType : $result[0]['parent_word'];
            }
            $temp = implode('|', $temp);
            /* 替换成中文 */
            $string = str_replace('{' . $v . '}', '{' . $temp . '}', $string);
        }
        return $string;
    }

    /* 如果是在叶子结点的父节点下添加新的目录，则其对应的叶子结点要全部移到新建的目录下 */
    private function moveChildrenToNewNode($oldParentId, $newParentId)
    {
        if ($oldParentId == 'ROOT') {
            return true;
        }
        $condition = array(
            'parents' => $oldParentId,
            'is_leaf' => true,
            'is_valid' => true
        );
        $result = $this->TopicUnit->find($condition);
        if (empty($result)) {
            return true;
        }
        
        $condition = array(
            'parents' => $oldParentId,
            'is_leaf' => true
        );
        $value = array(
            'parents' => $newParentId
        );
        $result = $this->TopicUnit->update($condition, $value, true);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    /*
     * 根据逻辑句式获取其对应的同义词
     */
    public function getSynonyms()
    {
        $logics = $_REQUEST['logics'];
        $topicId = $_REQUEST['topicId'];
        $detection = $this->TopicDetection->findOne(array(
            'topic_id' => $topicId
        ));
        $patterns = implode(',', $detection['patterns']);
        $pat = "/\{([^(\})]*)\}/"; // 匹配'{XXX}'
        preg_match_all($pat, $logics, $wordArr);
        preg_match_all($pat, $patterns, $patternArr);
        $conditionArr = array();
        foreach ($wordArr[1] as $k => $v) {
            $wordTemp = explode('|', $v);
            $patternTemp = explode('|', $patternArr[1][$k]);
            foreach ($wordTemp as $k => $v) {
                $conditionArr[$patternTemp[$k]] = $v;
            }
        }
        $result = array();
        foreach ($conditionArr as $pattern => $parentWord) {
            $condition = array(
                'full_type' => $pattern,
                'parent_word' => $parentWord
            );
            $wordDict = $this->WordDict->findOne($condition);
            $res['full_word'] = implode('/', explode(".", $wordDict['full_word'])) . '/{' . $parentWord . '}';
            $res['synonyms'] = $wordDict['synonyms'];
            $res['word'] = $parentWord;
            $result[] = $res;
        }
        if (! empty($result)) {
            echo json_encode($result);
        }
    }

    public function getClassificationTreeBySearch()
    {
        $this->searchWord = trim($_POST['value']); // 模拟炒股
        if (empty($this->searchWord)) {
            echo json_encode(array());
            die();
        }
        $this->allParents = array();
        $condition = array(
            'is_leaf' => false,
            'is_valid' => true
        );
        $showField = array(
            'parents',
            'topic_name'
        );
        
        /* 父子节点分类 */
        $target = $this->TopicUnit->find($condition, $showField);
        $newNode = array();
        foreach ($target as $k => $info) {
            if ($info['parents'] == 'ROOT' && ! $this->treePermission($info['_id'])) {
                continue;
            }
            $newNode[$info['parents']][] = array(
                '_id' => $info['_id'],
                'name' => $info['topic_name'],
                'parents' => $info['parents']
            );
        }
        unset($info);
        
        $this->nodes = $newNode; // 写入全局变量
        
        /* 获取完整的目录树结构 */
        $tree = $this->getChildrensData($this->nodes['ROOT']);
        $this->allParents = array_unique($this->allParents);
        sort($this->allParents);
        
        echo json_encode(array(
            'tree' => $tree,
            'parents' => $this->allParents
        ));
    }

    /**
     *
     * @param array $pnodes
     *            当前父节点数组数据
     * @return mixed
     */
    public function getChildrensData($pnodes)
    {
        foreach ($pnodes as $key => $info) {
            $isChild = $this->getChildrensDataNode($info);
            if (! empty($isChild)) {
                $pnodes[$key]['children'] = $this->getChildrensData($isChild);
            }
        }
        return $pnodes;
    }

    /**
     *
     * @param array $pnode
     *            对当前父节点数据局部处理 返回父节点数据
     * @return array
     */
    public function getChildrensDataNode($pnode)
    {
        $arr = array();
        if (isset($this->nodes[$pnode['_id']])) {
            $arr = $this->nodes[$pnode['_id']];
            foreach ($arr as &$info) {
                if (! isset($pnode['parents_id'])) {
                    $info['parents_id'] = array(
                        $pnode['parents'],
                        $info['parents']
                    );
                } else {
                    $info['parents_id'] = array_merge($pnode['parents_id'], array(
                        $info['parents']
                    ));
                }
                if (strpos($info['name'], $this->searchWord) !== false) {
                    $this->allParents = array_merge($this->allParents, $info['parents_id'], array(
                        $info['_id']
                    ));
                }
            }
            unset($info);
        }
        return $arr;
    }

    /**
     * :逻辑句式中间被删除打个补丁，过滤多余的句式
     * 
     * @param array $param            
     * @return array $result
     */
    private function detectionFilter($param)
    {
        $pattern = "/\{([^\{\}]*)\}/"; // 匹配'{XXX}'
        preg_match_all($pattern, $param['wordPath'], $wordPath);
        preg_match_all($pattern, $param['oldWord'], $oldWord);
        $wordPath = $wordPath[1];
        $oldWord = $oldWord[1];
        $countOfWordPath = count($wordPath);
        $countOfoldWord = count($oldWord);
        /* 如果个数一致就不处理了 */
        if ($countOfWordPath == $countOfoldWord) {
            return $param;
        }
        $oldWordPinyin = array(); // 将$oldWord转换成拼音
        $offset = 0;
        foreach ($wordPath as $k => $v) {
            $eachOldWord = end(explode('|', $oldWord[$offset]));
            $eachOldWord = ChineseToPinyin::getCapital($eachOldWord);
            $tempWordPathEnd = end(explode('|', $v));
            $tempWordPathEnd = end(explode('.', $tempWordPathEnd));
            if ($eachOldWord == $tempWordPathEnd) {
                $offset ++;
            } else {
                unset($wordPath[$k]);
            }
        }
        foreach ($wordPath as $k => $v) {
            $wordPath[$k] = '{' . $v . '}';
        }
        $result = array(
            'wordPath' => implode('', $wordPath),
            'oldWord' => $param['oldWord']
        );
        return $result;
    }
}

